<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

class JobBoardControllerJAPayment extends JobBoardController {
/**
     * Constructor
     */
    function __construct(  )
    {    	
        parent::__construct(  ); 
          
    }
    
    /**
    * Display current jasalary of the component to administrator
    * 
    */
    function display(){   
    	$user = JFactory::getUser();
        if ($user->id==0)
        {
        	$this->setRedirect(JRoute::_("index.php?option=com_user&view=login"));
        	return ;
        }	
    	checkPermission('payment');  	    	
		parent::display();
    }
    
    function credit_checkout(){		
    	
    	checkPermission('payment');
    	
    	global $jbconfig, $option;
    	
    	$pay_id = JRequest::getInt('payment_method', 0);
		$payment_method = get_payment_gateways($pay_id);
		if(!$payment_method){
			JError::raiseNotice(1, JText::_('Payment method not found or Payment Method not support. Please contact Administrator.'));
			$this->setRedirect(JRoute::_("index.php?option=$option&view=japosts"));		
		}	
		
    	$PATH = JPATH_COMPONENT.DS."asset".DS."payments".DS.$payment_method[0]->name.".php";
		if(!file_exists($PATH)){
			JError::raiseNotice(1, JText::_('Payment Method not support. Please contact Administrator.'));
			$this->setRedirect(JRoute::_("index.php?option=$option&view=japosts"));		
		}
		
		$currency = $jbconfig['currency']->get('currency_code', 'USD');
		
		$id = JRequest::getInt('cid', 0);
		$product = $this->getModel('japayment')->getPackage('ja_credits', $id);
		$user = JFactory::getUser();
		if ( $user->id == 0 ){
            $uri = JFactory::getURI();
            $url = $uri->toString();
            $url = base64_encode($url);
        	$this->setRedirect(JRoute::_("index.php?option=com_user&view=login&return=".$url));        	
        	return ;
        }
		$transaction = $this->getModel('japayment')->add_waiting_payment(0, $currency, $payment_method[0]->id, 'C', $product);
    	if( $transaction ){    		
			require_once($PATH);
			$payment = new $payment_method[0]->name($payment_method[0]);						
			
			$vars = array();
			
			if($payment->config){
				foreach ($payment->config as $k=>$value){
					$vars[$k] = $value;
				}
			}
			$values['item_name'] = $product->title;
    		$values['item_number'] = 'C'.$transaction->id;
    		$customer = JFactory::getUser($transaction->user_id);
    		$values['custom'] = $customer->name;
    		$values['amount'] = $transaction->amount;
    		$values['currency_code'] = $currency;    	
    		$values['proudct_id'] = $id;
    		$values['product_price'] = $product->price;
    		
    		// Check coupon system
    		if( JRequest::getVar("coupon_code", "") != ""){
    		    $coupon_code = JRequest::getVar("coupon_code", "");
    		    $result = $this->getModel('japayment')->checkCouponCode($coupon_code, $product);
    		    if( $result !== false ){
    		        $values['amount']         = $values['amount'] - $result->discount_amount;
    		        $values['coupon_code']    = $coupon_code;
    		    }else JRequest::setVar("coupon_code", "");
    		}
    		
    		if ($payment_method[0]->name!='wirebank')
    			$vars = $payment->assign_params($vars,$values,$payment);
    		
    		$pay_url = $payment->config->server;
    		?>
    		<div style="width:100%; text-align:center">
    			<img src="<?php echo JURI::base()?>components/<?php echo $option?>/images/loader.gif" title="<?php echo JText::_('Loading')?>" alt="<?php echo JText::_('Loading')?>"/>
    			<br />
    			<?php echo JText::_('Please wait while the system is automatically transferred to the payment page');?>
    		</div>
    		<?php
    		
    		if ($payment_method[0]->name!='wirebank')
    			return encode_and_redirect($pay_url, $vars);    		    		
    		else 
    		{
    			$param = "&transaction_id=".$transaction->id;
    			?>
				<script type="text/javascript">
			    	location.href = '<?php	echo "$pay_url$param";	?>';
			    </script>
			    <?php
			    return;
    		}    		    		
    	}
    	
    	JError::raiseNotice(1, JText::_("ERROR something happen in the process. Please contact Administrator For more information"));
    	JRequest::setVar('layout', 'credit_confirm');
    	parent::display();
    }
    
    function posting_plan_checkout(){
    	global $jbconfig, $option;
    	
    	$pay_id = JRequest::getInt('payment_method', 0);
		$payment_method = get_payment_gateways($pay_id);
			
    	$PATH = JPATH_COMPONENT.DS."asset".DS."payments".DS.$payment_method[0]->name.".php";
		if(!file_exists($PATH)){
			JError::raiseNotice(1, JText::_('Payment Method not support. Please contact Administrator.'));
			$this->setRedirect(JRoute::_("index.php?option=$option&view=japosts"));		
		}
		
		$currency = $jbconfig['currency']->get('currency_code', 'USD');
		
		$id = JRequest::getInt('cid', 0);
		$model = $this->getModel('japayment');
		$product = $model->getPackage('ja_posting_plans', $id);
		$user = JFactory::getUser();
		if ( $user->id == 0 ){
            $uri = JFactory::getURI();
            $url = $uri->toString();
            $url = base64_encode($url);
        	$this->setRedirect(JRoute::_("index.php?option=com_user&view=login&return=".$url));        	
        	return ;
        }
    	$transaction = $this->getModel('japayment')->add_waiting_payment(0, $currency, $payment_method[0]->id, 'P', $product);
    	if( $transaction ){    		  		
			require_once($PATH);
			$payment = new $payment_method[0]->name($payment_method[0]);
									
    		$vars = array();
			if($payment->config){
				foreach ($payment->config as $k=>$value){
					$vars[$k] = $value;
				}
			}
    		
    		$values['item_name'] = $product->title;
    		$values['item_number'] = 'P'.$transaction->id;
    		$customer = JFactory::getUser($transaction->user_id);
    		$values['custom'] = $customer->name;
    		$values['amount'] = $transaction->amount;
    		$values['currency_code'] = $currency;    	
    		$values['product_id'] = $id;
    		$values['product_price'] = $product->price;
    		
    		// Check coupon system
    		if( JRequest::getVar("coupon_code", "") != ""){
    		    $coupon_code = JRequest::getVar("coupon_code", "");
    		    $result = $this->getModel('japayment')->checkCouponCode($coupon_code, $product);
    		    if( $result !== false ){
    		        $values['amount']         = $values['amount'] - $result->discount_amount;
    		        $values['coupon_code']    = $coupon_code;
    		    }else JRequest::setVar("coupon_code", "");
    		}
    		
//    		$values['demo'] = $payment->config->demo;
            
            // Check 

			if ($payment_method[0]->name!='wirebank')
    			$vars = $payment->assign_params($vars,$values,$payment);
    		
//    		var_dump($vars);
    		
    		$pay_url = $payment->config->server;
    		    		    		
    		?>
    		<div style="width:100%; text-align:center">
    			<img src="<?php echo JURI::base()?>components/<?php echo $option?>/images/loader.gif" title="<?php echo JText::_('Loading')?>" alt="<?php echo JText::_('Loading')?>"/>
    			<br />
    			<?php echo JText::_('Please wait while the system is automatically transferred to the payment page');?>
    		</div>
    		<?php 
    		if ($payment_method[0]->name!='wirebank')
    			return encode_and_redirect($pay_url, $vars);    		    		
    		else 
    		{
    			$param = "&transaction_id=".$transaction->id;
    			?>
				<script type="text/javascript">
			    	location.href = '<?php	echo "$pay_url$param";	?>';
			    </script>
			    <?php
			    return;
    		}
    	}
    	
    	JError::raiseNotice(1, JText::_("ERROR something happen in the process. Please contact Administrator For more information"));
    	parent::display();
    	
    }
	
    function posting_plan_checkout_by_credit(){    	
    	global $jbconfig, $option;
		
    	$Itemid = JRequest::getInt('Itemid', 0);
    	$user = JFactory::getUser();
    	if(!isset($user->id)){
    		JError::raiseNotice(1, JText::_("you need to log in before using this feature."));
    		return $this->setRedirect(JRoute::_("index.php?option=com_users"));
    	}
    	
		$product = $this->getModel('japosts')->getItem();
		$product_id = $product->id;
				
		$account = getAccountByUserID($user->id);
		
		$data = new stdClass();	    
	    $data->user_id = $user->id;
	    $data->credit_balance = (int)$account->credit_balance - (int)$product->price;
	    
	    // Check coupon system
		if( JRequest::getVar("coupon_code", "") != ""){
		    $coupon_code = JRequest::getVar("coupon_code", "");
		    $result = $this->getModel('japayment')->checkCouponCode($coupon_code, $product);
		    if( $result !== false ){
		        $data->credit_balance     = (int)$account->credit_balance - (int)$product->price + $result->discount_amount;
		    }else JRequest::setVar("coupon_code", "");
		}
	      
	    if($data->credit_balance<0) {
	    	JError::raiseNotice(1, JText::_("Your {$jbconfig['currency']->get('currency_symbol', 'Credit')} is not enough to make this transaction. Please purchase more {$jbconfig['currency']->get('currency_symbol', 'Credit')}s to continue this transaction."));
			return $this->setRedirect(JRoute::_("?option=com_jajobboard&view=japosts&layout=buycredit&cid[]=$product_id&Itemid=$Itemid"));
	    }
	    
	    if($product->type=='standard')	    $data->standard_posts_balance = $product->value + (int)$account->standard_posts_balance;
	    if($product->type=='premium')		$data->premium_posts_balance = $product->value + (int)$account->premium_posts_balance;

	    if($product->type=='resume'){
	    	$time_end_date = 0;
	    	$end_date = $account->end_date_search_resume;
	    	if($end_date) $time_end_date = strtotime($end_date);
	    	
	    	if(time()<$time_end_date){
	    		$data->end_date_search_resume =  date('Y-m-d H:i:s', strtotime (  $account->end_date_search_resume . " +{$product->value} days" ));
	    	}
	    	else{
	    		$data->begin_date_search_resume = date('Y-m-d H:i:s');
		    	$data->end_date_search_resume   = date('Y-m-d H:i:s', strtotime ( date ( "Y-m-d H:i:s" ) . " +{$product->value} days" ));		    	
	    	}
	    }    	
    	
    	if (!update_account_for_employer($data)) {
			JError::raiseNotice(1,JText::_("An error occurred during the update of your account. Please contact admin for more details."));
			return $this->setRedirect(JRoute::_("index.php?option=$option&view=japayment&layout=posting_plan_confirm&cid=$product_id&Itemid=$Itemid"));
		}
		
    	if($jbconfig['currency']->get('mode', 'real_currency')=='real_currency'){
    		$currency = $jbconfig['currency']->get('currency_code', 'USD');
    	}
    	else $currency = $jbconfig['currency']->get('currency_name', 'Credit');
    	$user = JFactory::getUser();
		if ( $user->id == 0 ){
            $uri = JFactory::getURI();
            $url = $uri->toString();
            $url = base64_encode($url);
        	$this->setRedirect(JRoute::_("index.php?option=com_user&view=login&return=".$url));        	
        	return ;
        }
    	$transaction = $this->getModel('japayment')->add_waiting_payment(1, $currency, 'Manual', 'P', $product );
		
    	if (!is_object($transaction)) {
			JError::raiseNotice(1, JText::_("An error occurred while creating the invoice. Please contact admin for more details."));
			return $this->setRedirect(JRoute::_("index.php?option=$option&view=japayment&layout=posting_plan_confirm&cid=$product_id&Itemid=$Itemid"));
		}
		
		$this->getModel('japayment')->email_posting_order_completed($transaction, $product);
		
		$this->setRedirect(JRoute::_("index.php?option=$option&view=jaemployers&layout=account&Itemid=$Itemid"), JText::_('Successfully bought posting plan. You will receive an confirmation email within minutes. Thank you for using our service'));
    }            	
    
	function payment_notify(){
		$model = $this->getModel('japayment');
		
		$pay_name = JRequest::getVar('payment_method', '');
		$payment_method = get_payment_gateways(0, $pay_name);
		jimport('joomla.filesystem.file');	
		if (!JFile::exists(JPATH_COMPONENT.DS."asset".DS."payments".DS.$payment_method[0]->name.".php"))
		{
			return ;
		}
		require_once(JPATH_COMPONENT.DS."asset".DS."payments".DS.$payment_method[0]->name.".php");
		$payment = new $payment_method[0]->name($payment_method[0]);
		
		$result = $payment->check_payment();
		
		if (!$result) {
			$model->payment_error();
		}
		elseif($result && !$result->completed){
			$model->pending_payment($result);
			JError::raiseWarning(1, JText::_("Your process is not complete because your transaction is in status pending."));
		}elseif($result) {
			$result->payment_method = $payment_method[0]->id;			
			$check = $model->complete_payment($result);
			if($check) 
			{
				if ($pay_name=='_2checkout')
					$payment->payment_return();
			}
			else JError::raiseWarning(1, JText::_("ERROR something happen in the process. Please contact Administrator For more information"));
		}
		$this->setRedirect(JRoute::_('index.php?option=com_jajobboard&view=japayment&layout=message'));
	}
	
	function payment_return(){
		$model = $this->getModel('japayment');
		$pay_name = JRequest::getVar('payment_method', '');
		$method_config = get_payment_gateways(0, $pay_name);
		require_once(JPATH_COMPONENT.DS."asset".DS."payments".DS.$method_config[0]->name.".php");
		$payment = new $method_config[0]->name($method_config[0]);
		$result = $payment->payment_return();
		if ($result!='wirebank'){
			if (!$result)
			{
				$model->payment_error();				
			}
			elseif(isset($result->id)){
				
				if ( !$result->completed ){
					
					$model->pending_payment($result);					
				}
				else{
					
					$result->payment_method = $method_config[0]->id;
					$check = $model->complete_payment($result);
				}
				
			}
		}
		// $this->setRedirect(JRoute::_('index.php?option=com_jajobboard&view=japayment&layout=message'));
	}
	
	function payment_cancel(){
		$pay_name = JRequest::getVar('payment_method', '');
		
		$method_config = get_payment_gateways(0, $pay_name);
//		var_dump($method_config[0]->name);
		require_once(JPATH_COMPONENT.DS."asset".DS."payments".DS.$method_config[0]->name.".php");
		$payment = new $method_config[0]->name($method_config[0]);
		$payment->payment_cancel();
		$this->setRedirect(JRoute::_('index.php?option=com_jajobboard&view=japayment&layout=message'));
	}
}